package com.suning.park.admin.mgr.loginmodule.controller;

import com.suning.park.admin.util.JsonUtil;
import com.suning.park.admin.base.IAbstractController;
import com.suning.park.admin.mgr.loginmodule.service.MgrLoginService;
import com.suning.park.admin.util.StringUtil;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

/**
 * 系统用户登陆
 *
 * @author niecheng
 * @version 1.0 2016-04-14
 * @since jdk1.7.0_79
 */
@Controller
@RequestMapping(value = "/mgr/login", produces = {"application/json;charset=UTF-8"})
public class MgrLoginController extends IAbstractController {

    private static final Logger logger = LoggerFactory.getLogger(MgrLoginController.class);

    @Resource(name = "mgrLoginServiceImpl")
    private MgrLoginService mgrLoginService;

    /**
     * 登录
     * @param request
     * @param login 账号
     * @param pwd 密码
     * @return
     */
    @RequestMapping(value = "in", method = RequestMethod.POST)
    @ResponseBody
    public String in(HttpServletRequest request, String login, String pwd) {
        Date currentDate = new Date();
        Map<String, Object> result = null;
        logger.info("登录请求参数, login:{}; pwd:{};", new Object[]{login, pwd});
        if (StringUtil.hasEmpty(login, pwd)) {
            result = new HashedMap();
            result.put(IS_SUCCESS_DESC, SUCCESS);
            result.put(MESSAGE_DESC, "参数错误");
            return result.toString();
        }
        result = mgrLoginService.loginService(request, login, pwd, currentDate);
        return JsonUtil.objectToJson(result);
    }

    /**
     * 退出
     * @param userId 用户ID
     * @return
     */
    @RequestMapping(value = "out/{userId}", method = RequestMethod.GET)
    public ModelAndView out(HttpServletRequest request, ModelAndView view, @PathVariable String userId) {
        logger.info("退出请求参数, 用户ID:{}", new Object[]{userId});
        if (StringUtils.isEmpty(userId)) {
            logger.info("参数错误");
            view.setViewName("login");
        }
        final HttpSession session = request.getSession();
        session.invalidate();
        view.setViewName("login");
        return view;
    }
}
